<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="账号/昵称">
          <n-input v-model:value="search_param.account" placeholder="请输入账号或昵称查询" style="width:230px"
                   clearable/>
        </n-form-item>
        <n-form-item label="电话">
          <n-input v-model:value="search_param.phone" placeholder="请输入电话查询" style="width:160px" clearable/>
        </n-form-item>
        <n-form-item label="角色">
          <n-select v-model:value="search_param.roleId" filterable placeholder="请选择角色" style="width:200px"
                    value-field="key" :options="roleOption" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" placeholder="请选择状态" style="width:130px"
                    :options="statusOptions" clearable/>
        </n-form-item>
        <n-form-item>
          <SearchButtonGroup @submit="handleSubmitSearch"
                             @reset="()=>(search_param.account=null,search_param.roleId=null,search_param.phone=null,search_param.status=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="admin_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="admins/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success"  v-permission="['admin:add']"  @click="()=>(addEditAdmin=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
  </n-card>
  <!--新增、修改管理员-->
  <n-modal v-model:show="addEditAdmin"
           :title="addEditForm.id?'修改管理员':'新增管理员'" :mask-closable="false"
           :show-icon="false" preset="dialog" @after-leave="closeAddEditAdmin">
    <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
            label-width="auto" label-placement="left">
      <n-form-item label="账号" path="account">
        <n-input v-model:value="addEditForm.account" placeholder="请填写管理员账号" clearable/>
      </n-form-item>
      <n-form-item label="昵称" path="nickName">
        <n-input v-model:value="addEditForm.nickName" placeholder="请填写管理员昵称" clearable/>
      </n-form-item>
      <n-form-item label="所属角色" path="roleId">
        <n-select v-model:value="addEditForm.roleId" placeholder="请选择所属角色" style="width: 100%"
                  value-field="key" :options="roleOption" clearable/>
      </n-form-item>
      <n-form-item label="登录密码" path="password">
        <n-input v-model:value="addEditForm.password"
                 :placeholder="addEditForm.id?'留空不影响，若填写、则会进行修改密码':'请填写登录密码'" clearable/>
      </n-form-item>
      <n-form-item label="电话" path="phone">
        <n-input v-model:value="addEditForm.phone" maxlength="11" placeholder="请填写管理员电话号码" clearable/>
      </n-form-item>
      <n-form-item label="电子邮箱" path="eMail">
        <n-auto-complete v-model:value="addEditForm.eMail" :options="emailOptions" placeholder="请填写管理员电子邮箱"
                         clearable/>
      </n-form-item>
      <n-form-item label="消息提醒" path="accMessage">
        <n-checkbox-group v-model:value="addEditForm.accMessage">
          <div class="m-t-5">
          <n-space item-style="display: flex;">
            <template v-for="item in accMessageOption">
              <n-checkbox  :value="item.value" :label="item.label" />
            </template>
          </n-space>
          </div>
        </n-checkbox-group>
      </n-form-item>
      <n-form-item label="状态" path="AccountNonLocked">
        <n-switch :round="false" v-model:value="addEditForm.AccountNonLocked" :checked-value="1" :unchecked-value="0">
          <template #checked>
            正常
          </template>
          <template #unchecked>
            锁定
          </template>
        </n-switch>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditAdmin=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitAdminLoading" @click="handelSubmitAdmin">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import {ref, h, reactive, onBeforeMount, computed} from 'vue'
import {delRequest, getRequest, postPutRequest} from '@/api/data.ts';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {NTag, NPopconfirm, SelectOption, FormItemRule, FormInst, useMessage} from 'naive-ui'
import DataTable from '@components/DataTable'
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {AddSharp} from "@vicons/material";
import {emails_suffix} from '@/config';

interface RoleOption {
  label?: string,
  key?: string | number,

}
const message = useMessage()
//查询条件
const search_param = ref({
  account: null,
  roleId: null,
  phone: null,
  status: null,
})
const roleOption = ref<RoleOption[]>([]);
//状态选项
const statusOptions = ref<SelectOption[]>([
  {
    label: '正常',
    value: 1
  },
  {
    label: '锁定',
    value: 0
  },
])
//数据列表
const admin_list = ref<any>();
const columns = ref([
  {
    title: '账号',
    key: 'account',
  }, {
    title: '昵称',
    key: 'nickName',
  }, {
    title: '所属角色',
    key: 'roleName',
    width: 130,
    render(row: { roleName: string | null, isSupper: number | null }) {
      let role_name: string | null;
      if (row.isSupper && row.isSupper === 1) {
        role_name = '超级超级管理员';
      } else {
        role_name = row.roleName;
      }
      return h('span', null, {
        default: () => (role_name),
      })
    }
  },
  {
    title: '状态',
    key: 'accountNonLocked',
    width: 80,
    render(row: { accountNonLocked: boolean }) {
      const enabled_color = row.accountNonLocked ? 'success' : 'warning';
      const enabled_text = row.accountNonLocked ? '正常' : '锁定';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text),
          }
      );
    }
  },
  {
    title: '电话',
    key: 'phone',
    width: 130,
  }, {
    title: '邮箱',
    key: 'email',
    width: 160,
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }, {
    title: '更新时间',
    key: 'updateTime',
    width: 175,
  },
])
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          disabled: !!record.isDisabled,
          permission: ['admin:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前管理员吗？',
          },
          disabled: !!record.isDisabled,
          permission: ['admin:del']
        },
      ]
    });
  },
});
//新增、修改管理员
const accMessageOption=ref<SelectOption[]>([
  {
    label: '新增订单消息',
    value: 1
  },
  {
    label: '新增教师消息',
    value:2
  },  {
    label: '新增提现申请消息',
    value: 3
  },
  {
    label: '新的反馈',
    value:4
  },
])
const addEditAdmin = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitAdminLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  account: '',
  nickName: '',
  roleId: null,
  password: null,
  phone: '',
  eMail: '',
  AccountNonLocked: 1,
  accMessage:<number|any>[]
});
const addEditFormRules = computed(() => {
  return {
    account: {
      required: true,
      trigger: ['blur', 'input'],
      asyncValidator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          let regex = /^[A-Za-z0-9]+$/;
          if (!value) {
            reject(Error('请填管理员名称'))
          } else if (!regex.test(value)) {
            reject(Error('管理员名称只能是英文加数字')) // reject with error message
          } else {
            getRequest('admins/check_account', {
              id: addEditForm.value.id,
              account: addEditForm.value.account
            }, true).then((result: { status: number, message: string, code: number }) => {
              if (result.code === 200) {
                resolve()
              } else {
                reject(Error(result.message))
              }
            })
          }
        })
      }
    },
    nickName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写管理员昵称'
    },
    roleId: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择所属角色'
    },
    password: {
      required: !addEditForm.value.id,
      trigger: ["blur", "input"],
      validator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          if (!value && !addEditForm.value.id) {
            reject(Error("请填写登录密码"));
          } else if (value && value.length < 6) {
            reject(Error("请填写6位或6位以上的登录密码"));
          } else {
            resolve();
          }
        });
      },
    },
  }
})
const emailOptions = computed(() => {
  return emails_suffix.map((suffix) => {
    if (addEditForm.value.eMail) {
      const prefix = addEditForm.value.eMail.split("@")[0];
      return {
        label: prefix + suffix,
        value: prefix + suffix,
      };
    }
  });
});
//修改管理员
const handleEdit = (record: Recordable) => {
  // 拆分字符串并转换为整数数组
  let accMessage: any[]=[];
  if (record.accMessage){
    let strArray: string[] = record.accMessage.split(",");
    accMessage = strArray.map(Number);
  }

  addEditForm.value.id = record.id;
  addEditForm.value.account = record.account;
  addEditForm.value.nickName = record.nickName
  addEditForm.value.roleId =record.roleId;
  addEditForm.value.phone =record.phone;
  addEditForm.value.eMail = record.email;
  addEditForm.value.AccountNonLocked =record.accountNonLocked ? 1 : 0;
  addEditForm.value.accMessage =accMessage;
  addEditAdmin.value=true;
}
//删除管理员
const handleDelete = (record: Recordable) => {
  delRequest('admins/del',record.id).then((result:ResponseResult)=>{
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          admin_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//查询
const handleSubmitSearch = () => {
  admin_list.value.searchListData();
}
//关闭新增、修改管理员
const closeAddEditAdmin = () => {
  addEditForm.value.id = 0;
  addEditForm.value.account = '';
  addEditForm.value.nickName = '';
  addEditForm.value.roleId = null;
  addEditForm.value.password = null;
  addEditForm.value.phone = '';
  addEditForm.value.eMail = '';
  addEditForm.value.accMessage =[];
  addEditForm.value.AccountNonLocked = 1;
  handelSubmitAdminLoading.value = false;
}
//提交新增，修改数据
const handelSubmitAdmin = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitAdminLoading.value = true;
      const url = addEditForm.value.id ? 'admins/edit' : 'admins/add';
      postPutRequest(url,addEditForm.value,addEditForm.value.id ? 'PUT' : 'POST').then((result:ResponseResult)=>{
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditAdmin.value = false;
              if (addEditForm.value.id) {
                admin_list.value.reload();
              } else {
                admin_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitAdminLoading.value = false;
        }
      })
    }
  })
}
//获取角色
const getRole = async () => {
  await getRequest("role/get_role").then((result: ResponseResult) => {
    const {data} = result;
    roleOption.value = data;
  })
}
onBeforeMount(() => {
  getRole()
})
</script>

<style scoped lang="scss">

</style>
